package com.example.case2;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Created with IntelliJ IDEA.
 * ClassName: CuratorLock
 * Package: com.example.case2
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-30
 * Time: 12:18
 */

public class CuratorLock {
    public static void main(String[] args) {

        //创建分布式锁
        InterProcessMutex lock1 = new InterProcessMutex(getClient(),"/locks");

        InterProcessMutex lock2 = new InterProcessMutex(getClient(),"/locks");

        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取锁
                try {
                    lock1.acquire();
                    System.out.println("线程1获取到锁");
                    //说明可重入
                    lock1.acquire();
                    System.out.println("线程1再次获取到锁");

                    Thread.sleep(5000);

                    //释放锁
                    lock1.release();
                    System.out.println("线程1 释放锁");

                    lock1.release();
                    System.out.println("线程1 再次释放锁");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取锁
                try {
                    lock2.acquire();
                    System.out.println("线程2 获取到锁");
                    //说明可重入
                    lock2.acquire();
                    System.out.println("线程2 再次获取到锁");

                    Thread.sleep(5000);

                    //释放锁
                    lock2.release();
                    System.out.println("线程2 释放锁");

                    lock2.release();
                    System.out.println("线程2 再次释放锁");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();



    }

    private static CuratorFramework getClient() {

        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(3000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("hadoop102:2181,hadoop103:2181,hadoop104:2181")
                .connectionTimeoutMs(2000)
                .retryPolicy(retry).build();

        //启动客户端
        client.start();
        System.out.println("zookeeper 启动成功");

        return client;
    }
}
